package db

import (
	_ "github.com/go-sql-driver/mysql"
)
type RecruitResult struct{
	Id				int     `json:"id"`
	Position  		string 	`json:"position"`
	Content  		string 	`json:"content"`
	ReleaseDate  	string 	`json:"releaseDate"`
}

func GetRecruit()(as []RecruitResult,err error){
	rows, err := ulwebsiteDb.Query(`
	SELECT
	    a.id,ifnull(a.position,""),ifnull(a.content,""),ifnull(a.releaseDate,"")
    FROM
        recruit a
	`)
	if err != nil {
		return
	}
	defer rows.Close()
	as = make([]RecruitResult,0)
	for rows.Next() {
		var a RecruitResult
		err = rows.Scan(&a.Id,&a.Position, &a.Content,&a.ReleaseDate)
		if err != nil {
			return
		}
		as = append(as, a)
	}
	return
}

func PostRecruit(position string,content string,releaseDate string)(id int64,err error){
	tx, err := ulwebsiteDb.Begin()
	if err != nil {
		return
	}
	defer tx.Commit()
	rows, err := tx.Exec("insert into recruit(position,content,releaseDate) values(?,?,?)",position,content,releaseDate)
	if err != nil {
		tx.Rollback()
		return
	}
	id,err = rows.LastInsertId()
	if err != nil {
		return
	}
	return
}

func EditRecruit(position string,content string,uid string)(id int64,err error){
	tx, err := ulwebsiteDb.Begin()
	if err != nil {
		return
	}
	defer tx.Commit()
	rows, err := tx.Exec("UPDATE recruit SET position=?,content=? WHERE id=?",position,content,uid)
	if err != nil {
		tx.Rollback()
		return
	}
	id,err = rows.LastInsertId()
	if err != nil {
		return
	}
	return
}

func DelRecruit(uid string)(id int64,err error){
	tx, err := ulwebsiteDb.Begin()
	if err != nil {
		return
	}
	defer tx.Commit()

	rows, err := tx.Exec("DELETE FROM recruit WHERE id=?",uid)
	if err != nil {
		tx.Rollback()
		return
	}
	id,err = rows.LastInsertId()
	if err != nil {
		return
	}
	return
}
